package com.yaoxiaowen.project2.test.recycler_view;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yaoxiaowen.project2.util.log.debug.LogInterface;
import com.yaoxiaowen.project2.util.log.debug.LogTool;

/**
 * Created by Administrator on 2016/12/30.
 */

public class CommonViewHolder extends RecyclerView.ViewHolder{
    private  Context mContext;
    private  SparseArray<View> mViews;
    private View mContentView;
    private int mPosition;
    private int mLayoutId;

    public static final String TAG = "CommonViewHolder";
    private static final LogInterface mLog = LogTool.getLogType();
    private static final boolean DEBUG = false;

    public CommonViewHolder(Context mContext, View view) {
        super(view);
        this.mContext = mContext;
        mViews = new SparseArray<>();
        mContentView = view;
        mContentView.setTag(this);
    }


    public CommonViewHolder(Context context, View itemView, ViewGroup parent, int position) {
        super(itemView);
        mContext = context;
        mContentView = itemView;
        mPosition = position;
        mViews = new SparseArray<>();
        mContentView.setTag(this);
    }

    public static CommonViewHolder get(Context context, View contentView,
                                       ViewGroup parent, int layoutId, int position){
        if (contentView == null){
            View itemView = LayoutInflater.from(context).inflate(layoutId, parent, false);
            CommonViewHolder commonHolder = new CommonViewHolder(context, itemView, parent, position);
            commonHolder.mLayoutId = layoutId;
            return commonHolder;
        }else {
            CommonViewHolder commonHolder = (CommonViewHolder)contentView.getTag();
            commonHolder.mPosition = position;
            return commonHolder;
        }
    }

    public View getContentView(){
        return mContentView;
    }

    private int testCount = 1;
    public <T extends View> T getView(@IdRes int viewId){

        View view = mViews.get(viewId);
        if (view == null){
            view = mContentView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        //for test
        StringBuilder sb = new StringBuilder();
        testCount++;
//        sb.append("getView()  " + testCount + " == "  + getClass().getSimpleName() + this);
//        sb.append("   view->" + view.hashCode());
        mLog.i(DEBUG, TAG, sb.toString());


        return (T)view;
    }

    public void updatePosition(int position){
        mPosition = position;
    }

    /**
     * 各种 set方法
     */
    public CommonViewHolder setText(int viewId, String text){
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

}
